package com.tripcube.ai.controller;

import com.tripcube.ai.model.dto.CreateKnowledgeBaseDTO;
import com.tripcube.ai.service.KnowledgeBaseService;
import com.tripcube.common.core.web.controller.BaseController;
import com.tripcube.common.log.annotation.Log;
import com.tripcube.common.log.enums.BusinessType;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * 知识库管理控制器
 * 
 * @author alander
 */
@Tag(name = "知识库管理", description = "阿里百炼知识库管理相关接口")
@RestController
@RequestMapping("/ai/knowledgebase")
@RequiredArgsConstructor
public class KnowledgeBaseController extends BaseController {
    
    private final KnowledgeBaseService knowledgeBaseService;

    /**
     * 查询知识库列表
     */
    @Operation(summary = "查询知识库列表")
    @GetMapping("/list")
    public Object list(@RequestParam String indexName,
                       @RequestParam(defaultValue = "1") String pageNumber,
                       @RequestParam(defaultValue = "10") String pageSize) {
        try{
            return success(knowledgeBaseService.selectKnowledgeBaseList(indexName,pageNumber,pageSize));
        }catch (Exception e){
            return error("查询知识库列表失败");
        }
    }

    /**
     * 新增知识库
     */
    @Operation(summary = "新增知识库")
    @Log(title = "知识库管理", businessType = BusinessType.INSERT)
    @PostMapping
    public Object add(@Validated @RequestBody CreateKnowledgeBaseDTO createDTO) {
        if(Objects.equals(createDTO.getSourceType(), "DATA_CENTER_FILE")){
            if(createDTO.getDocumentIds() == null ||
                    createDTO.getDocumentIds().isEmpty() ||
                    createDTO.getDocumentIds().stream().allMatch(String::isEmpty)) {
                return error("文档类型，需导入应用数据下的指定文档");
            }
        }
        try{
            return success(knowledgeBaseService.createKnowledgeBase(createDTO));
        }catch (Exception e){
            return error("新增知识库失败");
        }
        
    }

    /**
     * 删除知识库
     */
    @Operation(summary = "删除知识库")
    @Log(title = "知识库管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{knowledgeBaseId}")
    public Object remove(@Parameter(description = "知识库ID") @PathVariable String knowledgeBaseId) {
        if(knowledgeBaseService.deleteKnowledgeBase(knowledgeBaseId) == 0){
            return error("删除知识库失败");
        }
        try{
            return success(knowledgeBaseService.deleteKnowledgeBase(knowledgeBaseId));
        }catch (Exception e){
            return error("删除知识库失败");
        }

    }

    /**
     * 批量删除知识库
     */
    @Operation(summary = "批量删除知识库")
    //@RequiresPermissions("ai:knowledgebase:remove")
    @Log(title = "知识库管理", businessType = BusinessType.DELETE)
    @DeleteMapping
    public Object remove(@Parameter(description = "知识库ID数组") @RequestParam String[] knowledgeBaseIds) {
        try{
            return toAjax(knowledgeBaseService.deleteKnowledgeBaseBatch(knowledgeBaseIds));
        }catch (Exception e){
            return error("批量删除知识库失败");
        }
    }

    /**
     * 查询索引下的文档列表
     */
    @Operation(summary = "查询索引下的文档列表")
    @GetMapping("/listIndexDocuments")
    public Object listIndexDocuments(@RequestParam String indexId,
                                         @RequestParam(required = false) String documentStatus,
                                         @RequestParam(required = false) String documentName,
                                         @RequestParam(defaultValue = "1") Integer pageNumber,
                                         @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            return knowledgeBaseService.listIndexDocuments(indexId, documentStatus, documentName, pageNumber, pageSize);
        } catch (Exception e) {
            return error("查询文档列表失败");
        }
    }

    /**
     * 删除知识库索引文档
     */
    @Operation(summary = "删除知识库索引文档")
    @PostMapping("/deleteIndexDocument")
    public Object deleteIndexDocument(@RequestParam String indexId,
                                          @RequestParam List<String> documentIds) {
        try {
            return success(knowledgeBaseService.deleteIndexDocument(indexId, documentIds));
        } catch (Exception e) {
            return error("删除索引文档失败");
        }
    }

    /**
     * 提交指定的 CreateIndex 任务以完成知识库创建
     */
    @Operation(summary = "提交索引创建任务")
    @PostMapping("/submitIndexJob")
    public Object SubmitIndexJob(@RequestParam String indexId) {
        try{
            return success(knowledgeBaseService.SubmitIndexJob(indexId));
        }catch (Exception e){
            return error("提交索引创建任务失败");
        }
    }

    @Operation(summary = "查询索引任务状态")
    @GetMapping("/getIndexJobStatus")
    public Object getIndexJobStatus(@RequestParam String indexId, @RequestParam String jobId) {
        try{
            return success(knowledgeBaseService.getIndexJobStatus(indexId,jobId));
        }catch (Exception e){
            return error("查询索引任务状态失败");
        }
    }

    /**
     * 向一个非结构化知识库追加导入已解析的文档
     */
    @Operation(summary = "提交索引追加任务")
    @PostMapping("/submitIndexAddDocumentsJob")
    public Object submitIndexAddDocumentsJob(@RequestParam String indexId,
                                                 @RequestParam String SourceType,
                                                 @RequestParam List<String> categoryIds,
                                                 @RequestParam List<String> documentIds) {
        try{
            return success(knowledgeBaseService.submitIndexAddDocumentsJob(indexId, SourceType, categoryIds, documentIds));
        }catch (Exception e){
            return error("提交索引追加任务失败");
        }
    }

    /**
     * 查询索引下的分片列表
     */
    @Operation(summary = "查询索引下的分片列表")
    @GetMapping("/listChunks")
    public Object listChunks(@RequestParam String indexId,
                                 @RequestParam(required = false) String fileId,
                                 @RequestParam(defaultValue = "1") Integer pageNum,
                                 @RequestParam(defaultValue = "10") Integer pageSize,
                                 @RequestParam(required = false) List<String> fields) {
        try {
            return success(knowledgeBaseService.listChunks(indexId, fileId, pageNum, pageSize, fields));
        } catch (Exception e) {
            return error("查询分片列表失败");
        }
    }

    /**
     * 修改切片
     */
    @Operation(summary = "修改切片")
    @PostMapping("/updateChunk")
    public Object updateChunk(@RequestParam String indexId,
                                  @RequestParam String dataId,
                                  @RequestParam String chunkId,
                                  @RequestParam Boolean isDisplayedChunkContent,
                                  @RequestParam String content,
                                  @RequestParam String title) {
        try {
            return success(knowledgeBaseService.updateChunk(indexId, dataId, chunkId, isDisplayedChunkContent, content, title));
        } catch (Exception e) {
            return error("修改切片失败");
        }
    }

    /**
     * 删除切片
     */
    @Operation(summary = "删除切片")
    @PostMapping("/deleteChunks")
    public Object deleteChunks(@RequestParam String indexId,
                                   @RequestParam List<String> chunkIds) {
        try {
            return success(knowledgeBaseService.deleteChunks(indexId, chunkIds));
        } catch (Exception e) {
            return error("删除切片失败");
        }
    }
}